<!--
 @description 经销商分店关店-编辑
 @fileName Add.vue
 @author zengqiongying
 @created 2023-04-27 19:31:42
-->
<template>
  <div class="has-foot-pb">
    <Card no-mg :round="false">
      <Cell title="门店名称" :modelValue="detail.name" defaultValue="--" readonly custom />
      <Cell title="详细地址" :modelValue="detail.shopAddr" defaultValue="--" readonly custom />
      <Cell title="门店经营面积(㎡)" :modelValue="detail.operateArea" defaultValue="--" readonly />
    </Card>
    <Card title="变更后业务类型" no-mg :round="false">
      <Cell is-column custom readonly>
        <div class="business-type-tag">
          <Tag
            v-for="(item, i) in businessTypeList"
            :key="i"
            :plain="getCheckedStatus(item.code)"
            :type="getCheckedStatus(item.code) ? 'primary' : 'default'"
            @click="onClickTag(item)"
          >
            <span v-if="checkNew(item.code)" class="new">新增</span>
            <span v-if="checkCancel(item.code)" class="cancel">取消</span>
            {{ item.name }}
          </Tag>
        </div>
      </Cell>
    </Card>
    <template v-if="isChange">
      <Card v-if="typeCode === 'D'" no-mg :round="false">
        <template #title>
          <div class="group-title"><span class="color-error">*</span>业务取消原因</div>
        </template>
        <Cell is-column custom divider :right="false" required>
          <qmp-field v-model="formData.cancelReason" type="textarea" placeholder="输入内容" class="ctm-text-area" />
        </Cell>
      </Card>
      <Card title="业务类型变更附件" no-mg :round="false">
        <template v-if="typeCode === 'D'">
          <Cell title="取消业务附件" is-column custom :right="false">
            <AttachmentUpload v-model="attachment.ACCESS068" typeCode="ACCESS068" :objectId="detail.id" />
          </Cell>
        </template>
        <template v-if="typeCode === 'C'">
          <Cell title="补充协议附件" is-column custom :right="false" required>
            <AttachmentUpload v-model="attachment.ACCESS065" typeCode="ACCESS065" :objectId="detail.id" />
          </Cell>
          <Cell title="补充协议模板下载" is-column custom readonly>
            <!-- 补充协议模板为根据补充协议附件查询 -->
            <AttachmentUpload v-if="templateFileList.ACCESS065.length" v-model="templateFileList.ACCESS065" readonly />
            <div v-else>暂无文件</div>
          </Cell>
          <Cell title="补充协议签订说明下载" is-column custom readonly>
            <AttachmentUpload v-if="templateFileList.ACCESS066.length" v-model="templateFileList.ACCESS066" readonly />
            <div v-else>暂无文件</div>
          </Cell>
        </template>
      </Card>
      <Card v-if="typeCode === 'C'" title="门店报图情况" no-mg :round="false">
        <!-- <Cell title="是否报图" custom :right="false" required>
          <qmp-switch v-model="formData.isReportPic">
            <template #background>
              <span class="qmp-switch__background"> {{ formData.isReportPic ? '是' : '否' }}</span>
            </template>
          </qmp-switch>
        </Cell> -->

        <FieldSelect
          v-model="formData.isReportPic"
          title="是否报图"
          :url="`/data-dict/app/v2/dictionary/BOOLEANS`"
          label-name="dictName"
          value-name="dictCode"
          method="get"
          :params="{ query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 }"
          required
        />

        <Cell
          title="特殊建档附件"
          sub-title="(如未报图/未交保证金等情况，业务请示申请审核通过的流程附件)"
          is-column
          custom
          :right="false"
        >
          <AttachmentUpload v-model="attachment.ACCESS067" typeCode="ACCESS067" :objectId="detail.id" />
        </Cell>
      </Card>
    </template>
    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onSave">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick, computed, onUnmounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import Card from '@/components/Card/index.vue'
  import AttachmentUpload from '@/components/AttachmentUpload/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import Tag from '@/components/Tags/Tag.vue'
  import { saveShopInfo } from '@/apis/ctmCustomerChange/index'
  import { getDictList } from '@/apis/dataDict'
  import { queryMdmServiceCustDocDefList } from '@/apis/common'
  import { getAttachmentTemplate, queryAttachmentList } from '@/apis/common'
  import GetKeyboardMixin from '@/utils/useKeyboard'
  const none: any[] = [undefined, null, '']
  interface anyObjectModle {
    [key: string]: any
  }
  export default {
    name: 'DealerShopChangeEditShop',
    components: { Card, Tag, Cell, AttachmentUpload, FieldSelect },
    setup() {
      const { proxy }: any = getCurrentInstance()
      const $router = useRouter()
      const $route = useRoute()
      const datas = reactive<anyObjectModle>({
        id: $route.query.id || '',
        typeCode: $route.query.type || 'C', //操作类型: C 新增 ， D 取消
        detail: {},
        BIZ_TYPE_LIST: [], // 业务类型集合（取mdm主数据）
        formData: {
          afterBusinessType: [], //变更后的业务类型编码
          cancelReason: '',
          isReportPic: ''
        },
        attachment: {
          ACCESS068: [], //取消业务附件
          ACCESS065: [], //补充协议附件
          ACCESS067: [] // 特殊建档附件
        },
        templateFileList: {
          ACCESS065: [], //补充协议模板下载
          ACCESS066: [] // 补充协议说明下载
        }
      })
      datas.keyboard = {
        show: false
      }
      datas.keyboard = GetKeyboardMixin()

      const downTemplate = async () => {
        const codes = ['ACCESS065', 'ACCESS066']
        codes.forEach(async (code) => {
          const configId = await getAttachmentTemplate(code)
          if (configId) {
            const data = await queryAttachmentList(configId)
            datas.templateFileList[code] = data
          }
        })
      }

      // 原始业务类型
      const beforeBusinessType = computed(() => {
        if (none.includes(datas.detail.businessType)) return []
        return datas.detail.businessType.split(',')
      })
      // 业务类型是否有变更
      const isChange = computed(() => {
        const afterBusinessType = datas.formData.afterBusinessType
        return !(afterBusinessType.length === beforeBusinessType.value.length)
      })

      // 当前可操作的业务类型
      const businessTypeList = computed(() => {
        let businessType: any = []
        if (!none.includes(datas.detail.businessType)) {
          businessType = datas.detail.businessType.split(',')
        }
        if (datas.typeCode === 'D') {
          // 取消业务:
          return datas.BIZ_TYPE_LIST.filter((v: any) => {
            return businessType.includes(`${v.code}`)
          })
        } else {
          // 新增业务:
          return datas.BIZ_TYPE_LIST.map((v: any) => {
            const obj = { ...v }
            if (businessType.includes(`${v.code}`)) {
              obj.readonly = true
            }
            return obj
          })
        }
      })

      const getFormData = () => {
        const { formData, attachment }: any = datas
        const afterTypeCodes = formData.afterBusinessType
        const afterTypeNames = businessTypeList.value
          .filter((v: any) => afterTypeCodes.includes(v.code))
          .map((v: any) => v.name)
        let isReportPic = datas.detail.isReportPic
        let cancelReason = ''
        let attachmentDTOS = []
        if (isChange.value) {
          if (datas.typeCode === 'D') {
            // 取消业务类型
            cancelReason = formData.cancelReason
            attachmentDTOS = attachment.ACCESS068 || []
          } else {
            // 新增业务类型
            isReportPic = formData.isReportPic // ? 1 : 0
            attachmentDTOS = [...attachment.ACCESS065, ...attachment.ACCESS067]
          }
          attachmentDTOS.forEach((v: any) => {
            v.modelId = datas.detail.id
          })
        }

        let data: anyObjectModle = {
          afterBusinessType: afterTypeCodes.join(','),
          afterBusinessTypeName: afterTypeNames.join(','),
          isChange: isChange.value ? 1 : 0,
          isReportPic,
          cancelReason,
          attachmentDTOS
        }

        return data
      }

      const onSave = () => {
        const data: anyObjectModle = getFormData()
        const { typeCode, attachment } = datas
        if (none.includes(data.afterBusinessType)) {
          proxy.$toast('至少选择一个业务类型')
          return
        }
        if (data.isChange) {
          if (typeCode === 'C') {
            // 新增业务类型
            if (attachment.ACCESS065.length === 0) {
              proxy.$toast('请上传补充协议附件')
              return
            }

            if (none.includes(data.isReportPic)) {
              proxy.$toast('是否报图不能为空')
              return
            }
            // if (data.isReportPic === 0 && datas.attachment.ACCESS067.length === 0) {
            //   proxy.$toast('请上传特殊建档附件')
            //   return
            // }
          } else {
            if (none.includes(data.cancelReason)) {
              proxy.$toast('请输入业务取消原因')
              return
            }
            // 取消业务类型
            // if (attachment.ACCESS068.length === 0) {
            //   proxy.$toast('请上传取消业务附件')
            //   return
            // }
          }
        }
        const params = { ...datas.detail, ...data }
        saveShopInfo(params).then((res: any) => {
          if (res.success === 1) {
            proxy.$toast('保存成功')
            proxy.$SimpleEvents.emit('ChangeShopUpdateShopInfo', params)
            nextTick(() => {
              $router.goBack()
            })
          }
        })
      }

      const getDetail = async () => {
        datas.BIZ_TYPE_LIST = await queryMdmServiceCustDocDefList('QY037')
        let d: any = {}
        try {
          const info: any = localStorage.getItem('changeShopInfo')
          d = JSON.parse(info)
        } catch {}

        if (d.code) {
          if (d.name) {
            proxy.$SimpleEvents.emit('routeMetaTitle', datas.typeCode === 'C' ? '门店新增业务变更' : '门店取消业务变更')
          }
          datas.detail = d
          datas.formData.isReportPic = d.isReportPic // [1, '1'].includes(d.isReportPic) ? true : false
          datas.formData.cancelReason = d.cancelReason || ''
          let afterBusinessType = d.afterBusinessType || d.businessType

          if (!none.includes(afterBusinessType)) {
            datas.formData.afterBusinessType = afterBusinessType.split(',')
          }
          if (datas.typeCode == 'D') {
            const oldCodes = d.businessType.split(',')
            datas.formData.afterBusinessType = datas.formData.afterBusinessType.filter((code: string) => {
              return oldCodes.includes(code)
            })
          }
        }
      }
      // 点击业务类型操作
      const onClickTag = (dict: any) => {
        if (dict.readonly) return
        const code = dict.code
        const codes = datas.formData.afterBusinessType || []
        const i = codes.findIndex((o: any) => o === code)
        if (i > -1) {
          codes.splice(i, 1)
        } else {
          codes.push(code)
        }
        datas.formData.afterBusinessType = codes
      }
      // 设置业务类型选中状态
      const getCheckedStatus = (dictCode: string) => {
        const codes = datas.formData.afterBusinessType || []
        return codes.includes(dictCode)
      }
      // 判断是否新增业务类型
      const checkNew = (dictCode: string) => {
        if (datas.typeCode !== 'C') return false
        const oldTypes = datas.detail.businessType.split(',')
        if (oldTypes.includes(dictCode)) {
          return false
        }
        return getCheckedStatus(dictCode)
      }
      // 判断是否取消业务类型
      const checkCancel = (dictCode: string) => {
        if (datas.typeCode !== 'D') return false
        if (getCheckedStatus(dictCode)) return false
        const oldTypes = datas.detail.businessType.split(',')
        return oldTypes.includes(dictCode)
      }

      onUnmounted(() => {
        localStorage.removeItem('changeShopInfo')
      })
      downTemplate()

      getDetail()
      return {
        ...toRefs(datas),
        businessTypeList,
        isChange,
        onClickTag,
        getCheckedStatus,
        checkNew,
        checkCancel,
        onSave
      }
    }
  }
</script>
<style lang="less" scoped>
  .group-title {
    padding: 0 16px;
    font: var(--font-main-title-strengthen);
    color: var(--texticon-default-strong);
  }
  .shop-list {
    padding: 0 16px;
    /deep/ .qmp-checkbox__label {
      flex: 1;
    }
    .shop-item {
      padding: 16px 0;
      position: relative;
      &.has-pr {
        padding-right: 56px;
      }
      .title {
        margin-bottom: 2px;
        font: var(--font-main-title-strengthen);
        color: var(--texticon-default-strong);
      }
      .address {
        font: var(--font-main-title-body);
        color: var(--texticon-default-strong);
      }
      .btn-edit {
        position: absolute;
        z-index: 9;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 24px;
        height: 24px;
        background-image: url(~@/assets/images/edit-line.png);
        background-size: 24px 24px;
        background-repeat: no-repeat;
      }
    }
  }
  .business-type-tag {
    .tag {
      margin-top: 10px;
    }
    .new,
    .cancel {
      position: absolute;
      right: -6px;
      top: -10px;
      padding: 2px;
      border-radius: 20px;
      font: var(--font-small);
      background: var(--texticon-contrary-strong);
    }
    .new {
      border: 1px solid var(--button-main-default);
      color: var(--texticon-color-brand-normal);
    }
    .cancel {
      border: 1px solid var(--texticon-color-secondary-normal);
      color: var(--texticon-color-secondary-normal);
    }
  }
</style>
